﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Eneta.Portal.Common;
using Eneta.Portal.Common.Dto;
using Eneta.Portal.Common.Repository;
using Microsoft.SharePoint;

namespace Eneta.Portal.Forum.Controls
{
    public class ForumsMainViewControl : UserControl
    {
        protected Repeater _categoriesRepeater;
        protected HtmlGenericControl _introBlock;
        protected HtmlAnchor _rssLink;
        protected HtmlAnchor _rssCommentsLink;
        protected HtmlAnchor _rssLinkBottom;
        protected HtmlAnchor _rssCommentsLinkBottom;

        private ForumRepository _forumRepository;
        private ForumRepository ForumRepository
        {
            get
            {
                if (_forumRepository != null)
                    return _forumRepository;

                _forumRepository = new ForumRepository(SPContext.Current.Web);
                return _forumRepository;
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            
            _categoriesRepeater.ItemDataBound += CategoriesRepeaterItemDataBound;
        }

        protected void CategoriesRepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            var category = (ForumCategoryDto)e.Item.DataItem;

            var forumsRepeater = (Repeater) e.Item.FindControl("_forumsRepeater");
            if(forumsRepeater == null)
            {
                Logger.LogWarning("Cannot find _forumsRepeater", GetType().ToString());
                return;
            }
            forumsRepeater.ItemDataBound += ForumsRepeaterItemDataBound;
            forumsRepeater.DataSource = category.Forums;
            forumsRepeater.DataBind();
        }

        protected void ForumsRepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            var forum = (ForumDto)e.Item.DataItem;

            var moderatorsRepeater = (Repeater) e.Item.FindControl("_moderatorsRepeater");
            moderatorsRepeater.DataSource = forum.Moderators;
            moderatorsRepeater.DataBind();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            Page.Title = Resources.Forum.ForumTitle + " | " + EnetaApplication.PortalTitle;

            if (IsPostBack)
                return;

            try
            {
                if (string.IsNullOrEmpty(Request.QueryString["category"]))
                    if (!string.IsNullOrEmpty(Request.QueryString["rss"]))
                    {
                        Response.Clear();
                        Response.ContentType = "application/rss+xml";
                        Response.Write(ForumRepository.GetCommonRss());
                        Response.End();
                        return;
                    }
                    else if (!string.IsNullOrEmpty(Request.QueryString["commentrss"]))
                    {
                        Response.Clear();
                        Response.ContentType = "application/rss+xml";
                        Trace.Write("ForumCommentsRss: start");
                        Response.Write(ForumRepository.GetCommentsRss());
                        Trace.Write("ForumCommentsRss: finish");
                        Response.End();
                        return;
                    }
            }
            catch(Exception ex)
            {
                Logger.LogWarning("OnLoad(): Error creating forum rss", GetType().ToString());
                Logger.LogException(ex);
                Response.End();
            }
            int id;
            IList<ForumCategoryDto> categories;
            try
            {
                categories = ForumRepository.GetForumCategories();
                if (int.TryParse(Request.QueryString["category"], out id))
                {
                    if (!string.IsNullOrEmpty(Request.QueryString["rss"]))
                    {
                        Response.Clear();
                        Response.ContentType = "application/rss+xml";
                        Response.Write(ForumRepository.GetForumCategoryRss(id));
                        Response.End();
                        return;
                    }
                    if (!string.IsNullOrEmpty(Request.QueryString["commentrss"]))
                    {
                        Response.Clear();
                        Response.ContentType = "application/rss+xml";
                        Response.Write(ForumRepository.GetForumCategoryCommentsRss(id));
                        Response.End();
                        return;
                    }

                    categories = (from c in categories
                                  where c.Id == id
                                  select c).ToList();
                    _introBlock.Visible = false;

                    var category = categories.FirstOrDefault();
                    if (category == null || string.IsNullOrEmpty(category.FeedBurnerUrl))
                    {
                        _rssLink.HRef = Request.RawUrl + "&rss=1";
                        _rssCommentsLink.HRef = string.Empty;
                        //_rssCommentsLink.HRef = Request.RawUrl + "&commentrss=1";
                        _rssCommentsLink.Visible = false;

                        _rssLinkBottom.HRef = _rssLink.HRef;
                        _rssCommentsLinkBottom.HRef = _rssCommentsLink.HRef;
                        _rssCommentsLinkBottom.Visible = false;
                    }
                    else
                    {
                        _rssLink.HRef = category.FeedBurnerUrl;
                        _rssLink.InnerText = category.Title;
                        //_rssCommentsLink.HRef = Request.RawUrl + "&commentrss=1";
                        _rssCommentsLink.HRef = string.Empty;
                        _rssCommentsLink.Visible = false;

                        _rssLinkBottom.HRef = _rssLink.HRef;
                        _rssCommentsLinkBottom.HRef = _rssCommentsLink.HRef;
                        _rssCommentsLinkBottom.Visible = false;

                        Page.Title = Resources.Forum.ForumTitle + " > " + category.Title + " | ";
                    }
                }
                _categoriesRepeater.DataSource = categories;
                _categoriesRepeater.DataBind();
            }
            catch(Exception ex)
            {
                Response.Write("<!-- " + ex + " -->");
                return;
            }


            var master = Page.Master;
            if (master != null)
            {
                try
                {
                    var link = (HtmlLink) master.FindControl("rssMetaUrl");
                    if (!string.IsNullOrEmpty(Request.QueryString["category"]))
                    {
                        link.Visible = true;
                        var cat = categories[0];
                        if (!string.IsNullOrEmpty(cat.FeedBurnerUrl))
                            link.Href = cat.FeedBurnerUrl;
                        else
                            link.Href = Request.RawUrl + "&rss=1";
                        link.Attributes["title"] = Resources.Forum.ForumTitle + ": " + categories[0].Title;

                    }
                    else
                    {
                        link.Visible = true;
                        link.Attributes["title"] = Resources.Forum.ForumTitle;
                    }
                }
                catch(Exception ex)
                {
                    Response.Write("<!-- " + ex + " -->");
                }
                try
                {
                    var dto = new RssLinksDto();
                    dto.RssTitle = _rssLink.InnerText;
                    dto.RssUrl = _rssLink.HRef;
                    dto.CommentsRssTitle = _rssCommentsLink.InnerText;
                    dto.CommentsRssUrl = _rssCommentsLink.HRef;

                    var typedMaster = master as MasterBaseWithDesignHack;
                    if (typedMaster != null)
                    {
                        typedMaster.SetRssLinks(dto);
                    }
                }
                catch(Exception ex)
                {
                    Response.Write("<!-- ex: " + ex + " -->");
                }
            }
        }

        private UserProfileRepository _profileRepository;
        public UserProfileRepository ProfileRepository
        {
            get
            {
                if (_profileRepository != null)
                    return _profileRepository;

                _profileRepository = new UserProfileRepository(SPContext.Current.Web);
                return _profileRepository;
            }
        }

        public string GetProfileImageUrl(int profileId)
        {
            var profile = ProfileRepository.GetUserProfileById(profileId);
            if (profile == null)
                return string.Empty;

            return profile.UserImage32x32Url;
        }

        public string GetShortTitle(string title)
        {
            if (string.IsNullOrEmpty(title))
                return title;

            if (title.Trim().Length == 0)
                return title;

            var len = 15;
            var suffix = string.Empty;

            if (title.Length < 15)
                len = title.Length;
            else if (title.Length > 15)
                suffix = "...";

            try
            {
                title = title.Substring(0, len).Trim() + suffix;
            }
            catch(Exception ex)
            {
                Logger.LogWarning("Exception in GetShortTitle()", string.Empty);
                Logger.LogException(ex);
            }

            return title;
        }
    }
}
